#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <cassert>
#include <functional>
using namespace std;

namespace liang
{
    class Thread
    {
    public:
        typedef function<void *(void *)> func_t; // 包装器
        Thread()
        {
            char buffer[128];
            snprintf(buffer, sizeof buffer, "thread: %d", threadnum++);
            _name = buffer;
        }
        // 这里不能使用this，所以设计成静态
        static void *start_routine(void *args)
        {
            Thread *_this = static_cast<Thread *>(args);
            return _this->callback();
        }
        void start(func_t func, void *args)
        {
            _func = func;
            _args = args;
            // 创建线程
            // 创建线程
            int n = pthread_create(&tid, nullptr, start_routine, this);
            assert(0 == n);
            (void)n; // 防止报warning
        }
        void *callback()
        {
            return _func(_args);
        }
        void join()
        {
            int n = pthread_join(tid, nullptr);
            assert(0 == n);
            (void)n;
        }
        string threadname()
        {
            return _name;
        }

    private:
        string _name;
        func_t _func;
        void *_args;
        pthread_t tid;
        static int threadnum;
    };

    int Thread::threadnum = 1;
}